/*
 * @Description:
 * @Author: Dxcr
 * @Date: 2024-05-24 11:20:54
 * @LastEditTime: 2024-06-27 17:51:14
 * @LastEditors: Dxcr
 */
const WebSocket = require("websocket").server;
const http = require("http");

const dataCount = 1000;
const speed = 100;

// 创建一个HTTP服务器
const server = http.createServer((req, res) => {
  res.writeHead(200, { "Content-Type": "text/plain" });
  res.end("WebSocket Server");
});

// 监听端口3000
const port = 3001;
server.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});

// 创建WebSocket服务器并与HTTP服务器绑定
const wsServer = new WebSocket({
  httpServer: server,
});

// 当有WebSocket连接时执行
wsServer.on("request", (request) => {
  const connection = request.accept(null, request.origin);
  console.log("Client connected");

  // 每200毫秒发送一个包含2000个不大于100的整数的数组到客户端
  const interval = setInterval(() => {
    const data = generateRandomArray(); // 生成数据
    connection.send(data); // 发送数据到客户端
    // connection.sendUTF(data); // 发送数据到客户端
  }, speed);

  // 当连接关闭时清除定时器
  connection.on("close", () => {
    clearInterval(interval);
    console.log("Client disconnected");
  });
});

wsServer.on("connection", (ws) => {
  console.log("客户端已连接");

  ws.on("message", (message) => {
    console.log(`收到消息: ${message}`);

    // 假设服务器收到心跳消息后，返回相同的消息给客户端
    if (message === "heartbeat") {
      ws.send("heartbeat"); // 返回心跳响应
    } else {
      // 处理其他消息
      ws.send("收到消息"); // 响应其他消息
    }
  });

  ws.on("close", () => {
    console.log("客户端已断开连接");
  });
});
let newData = new Int32Array(dataCount);
// 生成包含2000个不大于100的整数的数组函数
function generateRandomArray() {
  // 生成新的一组点，并添加到数组的末尾
  for (let i = 0; i < dataCount; i++) {
    newData[i] = Math.floor(Math.random() * 3000)
  }
  return Buffer.from(newData.buffer);
}
